package com.globaldom.web.sales;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.Sales;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/getallsales")
public class SalesGetAllController {
	public SalesGetAllController() {
	}

	private static final Logger log = Logger.getLogger(SalesGetAllController.class.getName());

	@RequestMapping(value = "/getall", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> getAllSales(HttpSession session, HttpServletRequest request) {
		Map<String, String> map;
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map = new HashMap<String, String>();
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}
		map = MemCacheManager.getMySales(personID);
		if (null != map && map.size() > 0)
			return map;
		else
			map = new HashMap<String, String>();

		PersistenceManager pmf = PMF.get().getPersistenceManager();
		try {

			Query query = pmf.newQuery(Sales.class, "person!=pid ");
			query.declareParameters("String pid");
			List<Sales> resources = ((List<Sales>) query.execute(personID));

			// FIXME. Directly add this to the map and return!!
			for (Sales sale : resources) {

				map.put(sale.getId().toString(),
						sale.getSaleType() + "/" + sale.getSaleAmount() + "/" + sale.getSalePrice() + "/"
								+ sale.getPerson());

			}
			MemCacheManager.putinMySales(map, personID);
		} catch (Exception ex) {
			log.severe("Unable to get all sales " + ex.getLocalizedMessage());
			ex.printStackTrace();
		} finally {

			pmf.close();
		}
		return map;

	}
}
